#include "otherquerywidget.h"
#include "ui_otherquerywidget.h"


OtherQueryWidget::OtherQueryWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::OtherQueryWidget)
{
    QFont font("Microsoft YaHei UI");
    font.setPixelSize(10);
    //ui->query_return_text->setFont(font);
    Reply_List << "city" << "area" << "address" <<"name";
    ui->setupUi(this);
    url = "http://api.map.baidu.com/place/v2/search?query=input&region=city&output=json&ak=g8kcyomXvkRVakb2Mazrkk6NVTBZZACM";
    ui->query_table->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->query_table->verticalHeader()->hide();
    ui->query_table->resizeColumnsToContents();
    ui->query_table->resizeRowsToContents();
    ui->query_table->verticalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->query_table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

}

OtherQueryWidget::~OtherQueryWidget()
{
    delete ui;
}

void OtherQueryWidget::on_weather_query_btn_clicked()
{
    ui->query_table->verticalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->query_table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    QString Wurl = "http://api.map.baidu.com/weather/v1/?district_id=city_id&data_type=all&ak=g8kcyomXvkRVakb2Mazrkk6NVTBZZACM";
    QString CityID = "110100";//getCityID函数返回值
    //QString CityID = this->getCityID(City);
    Wurl.replace(tr("city_id"),CityID);
    QNetworkRequest rq;
    QNetworkAccessManager* netmanger = new QNetworkAccessManager(this);;
    QNetworkReply* re;
    rq.setUrl(QUrl(Wurl));
    connect(netmanger,SIGNAL(finished(QNetworkReply*)),this,SLOT(getWeather(QNetworkReply*)));
    re = netmanger->get(rq);
    QStringList Header;
    Header<<"天气"<<"温度"<<"风向"<<"风力";
    ui->query_table->setColumnCount(4);
    ui->query_table->setHorizontalHeaderLabels(Header);
    ui->query_table->setRowCount(6);
}

void OtherQueryWidget::on_scenic_query_btn_clicked()
{
    ui->query_table->verticalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->query_table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    QNetworkRequest rq;
    QNetworkAccessManager* netmanger = new QNetworkAccessManager(this);;
    QNetworkReply* re;
    QString scenicUrl(this->url);
    scenicUrl.replace("input","旅游景点");
    scenicUrl.replace("city","西安");
    rq.setUrl(QUrl(scenicUrl));
    connect(netmanger,SIGNAL(finished(QNetworkReply*)),this,SLOT(getScenic(QNetworkReply*)));
    re = netmanger->get(rq);
    ui->query_table->setRowCount(3);
    ui->query_table->setColumnCount(2);
    QStringList Header;
    Header<<"名称"<<"地址";
    ui->query_table->setHorizontalHeaderLabels(Header);
}

void OtherQueryWidget::on_hotel_query_btn_clicked()
{
    ui->query_table->verticalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->query_table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    QNetworkRequest rq;
    QNetworkAccessManager* netmanger = new QNetworkAccessManager(this);;
    QNetworkReply* re;
    QString hotelUrl(this->url);
    hotelUrl.replace("input","酒店");
    hotelUrl.replace("city","西安");
    rq.setUrl(QUrl(hotelUrl));
    connect(netmanger,SIGNAL(finished(QNetworkReply*)),this,SLOT(getHotel(QNetworkReply*)));
    re = netmanger->get(rq);
}
void OtherQueryWidget::getScenic(QNetworkReply *re){
        QVariant statusCode = re->attribute(QNetworkRequest::HttpStatusCodeAttribute);
        qDebug() << "status code=" << statusCode.toInt();
        QByteArray ba = re->readAll();
        //qDebug()<<ba.length();
        QJsonParseError jsonpe;
        QJsonDocument json = QJsonDocument::fromJson(ba, &jsonpe);

        if (jsonpe.error == QJsonParseError::NoError)
        {
            if (json.isObject())
            {
                QJsonObject obj = json.object();
                if (obj.contains("error"))
                {
                    qDebug() << "error3:" << obj["error"];
                }
                else
                {
                    for (QJsonObject::Iterator it = obj.begin();
                         it != obj.end(); it++)
                    {
                        qDebug() << it.key() << " => " << it.value();
                    }
                    QJsonArray jarray = obj["results"].toArray();
                    ui->query_table->setRowCount(jarray.size());
                    for (int row = 0; row < jarray.size(); row++)
                    {
                        qDebug() << "====Row[" << row << "] Start===================";
                        QString addressString;
                        QString nameString;
                        QJsonObject jobj = jarray[row].toObject();
                        for (QJsonObject::Iterator it = jobj.begin();
                             it != jobj.end(); it++)
                        {

                            switch (Reply_List.indexOf(it.key())) {
                            case 0:
                                //addressString.insert(0,it.value().toString());
                                break;
                            case 1:
                                //addressString.insert(0,it.value().toString());
                                break;
                            case 2:
                                addressString.insert(0,it.value().toString());
                                break;
                            case 3:
                                nameString = it.value().toString();
                                break;
                            default:
                                break;
                            }
                            qDebug() << it.key() << " => " << it.value();
                        }
                       ui->query_table->setItem(row,0,new QTableWidgetItem(nameString));
                       ui->query_table->setItem(row,1,new QTableWidgetItem(addressString));
                       ui->query_table->item(row,0)->setTextAlignment(Qt::AlignCenter);
                       ui->query_table->item(row,1)->setTextAlignment(Qt::AlignCenter);
                    }
                    ui->query_table->resizeColumnsToContents();
                    ui->query_table->resizeRowsToContents();

                }
            }
            else
            {
                qDebug() << "error2, shoud json object";
            }
        }
        else
        {
            qDebug() << "error1:" << jsonpe.errorString();
        }

}
void OtherQueryWidget::getHotel(QNetworkReply *re){
    //返回酒店地址等信息
    //返回酒店地址等信息
    QVariant statusCode = re->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    qDebug() << "status code=" << statusCode.toInt();
    QByteArray ba = re->readAll();
    //qDebug()<<ba.length();
    QJsonParseError jsonpe;
    QJsonDocument json = QJsonDocument::fromJson(ba, &jsonpe);

    if (jsonpe.error == QJsonParseError::NoError)
    {
        if (json.isObject())
        {
            QJsonObject obj = json.object();
            if (obj.contains("error"))
            {
                qDebug() << "error3:" << obj["error"];
            }
            else
            {
                for (QJsonObject::Iterator it = obj.begin();
                     it != obj.end(); it++)
                {
                    qDebug() << it.key() << " => " << it.value();
                }
                QJsonArray jarray = obj["results"].toArray();
                ui->query_table->setRowCount(jarray.size());
                for (int row = 0; row < jarray.size(); row++)
                {
                    qDebug() << "====Row[" << row << "] Start===================";
                    QString addressString;
                    QString nameString;
                    QJsonObject jobj = jarray[row].toObject();
                    for (QJsonObject::Iterator it = jobj.begin();
                         it != jobj.end(); it++)
                    {

                        switch (Reply_List.indexOf(it.key())) {
                        case 0:
                            //addressString.insert(0,it.value().toString());
                            break;
                        case 1:
                            //addressString.insert(0,it.value().toString());
                            break;
                        case 2:
                            addressString.insert(0,it.value().toString());
                            break;
                        case 3:
                            nameString = it.value().toString();
                            break;
                        default:
                            break;
                        }
                        qDebug() << it.key() << " => " << it.value();
                    }
                   ui->query_table->setItem(row,0,new QTableWidgetItem(nameString));
                   ui->query_table->setItem(row,1,new QTableWidgetItem(addressString));
                   ui->query_table->item(row,0)->setTextAlignment(Qt::AlignCenter);
                   ui->query_table->item(row,1)->setTextAlignment(Qt::AlignCenter);
                }
//                ui->query_table->resizeColumnsToContents();
//                ui->query_table->resizeRowsToContents();

            }
        }
        else
        {
            qDebug() << "error2, shoud json object";
        }
    }
    else
    {
        qDebug() << "error1:" << jsonpe.errorString();
    }

}
void OtherQueryWidget::getWeather(QNetworkReply *re){
    //解析JSON数据，返回天气情况
    //qDebug()<<re->readAll();
    QJsonParseError jsonpe;
    QJsonDocument json = QJsonDocument::fromJson(re->readAll(), &jsonpe);

    if (jsonpe.error == QJsonParseError::NoError)
    {
        if (json.isObject())
        {
            QJsonObject obj = json.object();
            if (obj.contains("error"))
            {
                qDebug() << "error3:" << obj["error"];
            }
            else
            {
//                QString Wresult = obj["result"].toString();//此处冗杂，直接toObject更好
//                QJsonParseError jsonpe1;
//                QJsonDocument json1 = QJsonDocument::fromJson(Wresult.toLocal8Bit(),&jsonpe1);

                QJsonObject RObj = obj["result"].toObject();
//                if (jsonpe1.error == QJsonParseError::NoError)
//                {
//                    QJsonObject obj1 = json1.object();
                    for (QJsonObject::Iterator it = RObj.begin();
                        it != RObj.end(); it++)
                    {
                        if(it.key()==tr("now")){
                            //继续解析
                            QJsonObject nowObj = it.value().toObject();
                            QString Wea = nowObj["text"].toString();
                            if(nowObj["temp"].isNull())
                                qDebug()<<"温度是空！！！";
                            else{
                                qDebug()<<"不是空！！！";
                                qDebug()<<nowObj["temp"].toDouble();
                                QString str = nowObj["temp"].toString();
                                qDebug()<<str;
                            }
                            QString WindClass = nowObj["wind_class"].toString();
                            QString WindDir = nowObj["wind_dir"].toString();
                            ui->query_table->setItem(0,0,new QTableWidgetItem(Wea));

                            ui->query_table->setItem(0,1,new QTableWidgetItem(QString::number(nowObj["temp"].toDouble())));
                            ui->query_table->setItem(0,2,new QTableWidgetItem(WindDir));
                            ui->query_table->setItem(0,3,new QTableWidgetItem(WindClass));
                            ui->query_table->item(0,0)->setTextAlignment(Qt::AlignCenter);
                            ui->query_table->item(0,1)->setTextAlignment(Qt::AlignCenter);
                            ui->query_table->item(0,2)->setTextAlignment(Qt::AlignCenter);
                            ui->query_table->item(0,3)->setTextAlignment(Qt::AlignCenter);
                        }
                        else if(it.key()==tr("forecasts")){
                            QJsonArray ForeArr = it.value().toArray();
                            for(int index = 0;index<ForeArr.size();index++){
                                QJsonObject ForeObj = ForeArr[index].toObject();
                                QString Wea = ForeObj["text_day"].toString();
                                int Temp = ForeObj["high"].toInt();
                                QString WindClass = ForeObj["wc_day"].toString();
                                QString WindDir = ForeObj["wd_day"].toString();
                                ui->query_table->setItem(index+1,0,new QTableWidgetItem(Wea));
                                ui->query_table->setItem(index+1,1,new QTableWidgetItem(QString::number(ForeObj["high"].toDouble())));
                                ui->query_table->setItem(index+1,2,new QTableWidgetItem(WindDir));
                                ui->query_table->setItem(index+1,3,new QTableWidgetItem(WindClass));
                                ui->query_table->item(index+1,0)->setTextAlignment(Qt::AlignCenter);
                                ui->query_table->item(index+1,1)->setTextAlignment(Qt::AlignCenter);
                                ui->query_table->item(index+1,2)->setTextAlignment(Qt::AlignCenter);
                                ui->query_table->item(index+1,3)->setTextAlignment(Qt::AlignCenter);
                            }
                        }
                        //qDebug() << it.key() << " => " << it.value();
                    }
                    ui->query_table->resizeColumnsToContents();
                    ui->query_table->resizeRowsToContents();

//                }
//                else
//                {
//                        qDebug() << "error11:" << jsonpe1.errorString();
//                }
            }
        }
        else
        {
            qDebug() << "error2, shoud json object";
        }
    }
    else
    {
        qDebug() << "error1:" << jsonpe.errorString();
    }
}
QString OtherQueryWidget::getCityID(const QString City){
    QFile file("qrc:/urls/city_code.json");
    QString jsonStr;
    if(file.open(QIODevice::ReadOnly|QIODevice::Text))
    {
            QTextStream oustream(&file);
            oustream>>jsonStr;
            file.close();
            QByteArray bArr = jsonStr.toLocal8Bit();
            QJsonParseError jsonpe;
            QJsonDocument json = QJsonDocument::fromJson(bArr, &jsonpe);

            if (jsonpe.error == QJsonParseError::NoError)
            {
                if (json.isObject())
                {
                    QJsonObject obj = json.object();
                    if (obj.contains("error"))
                    {
                        qDebug() << "error3:" << obj["error"];
                    }
                    else
                    {
                        for (QJsonObject::Iterator it = obj.begin();
                             it != obj.end(); it++)
                        {
                            qDebug() << it.key() << " => " << it.value();
                            if(it.key()==City)
                                  return it.value().toString();
                        }
                    }
                }
                else
                {
                    qDebug() << "error2, shoud json object";
                }
            }
            else
            {
                qDebug() << "error1:" << jsonpe.errorString();
            }
    }
    else{
        qDebug()<<"josn读取失败";
    }
    return "";

}
